<template>
  <div class="slider" :style="{ width: percentage + '%' }"></div>
  <div class="player">
    <audio :src="musicUrl" ref="audioRef" @timeupdate="timeupdate" @ended="hdPlayNext"></audio>

    <!-- 底部信息 -->
    <div class="music-info" v-if="playList[playListIndex]">
      <div class="info-left" @click="toMusicDetail(playList[playListIndex])">
        <div class="music-img" :class="{ 'round-img': songPlay }">
          <img :src="playList[playListIndex].album.picUrl" />
        </div>

        <div class="music-ar">
          <!-- 歌曲标题 -->
          <div class="name van-ellipsis">
            {{ playList[playListIndex].musicName }}
          </div>
          <div class="info">
            <!-- 歌手信息 -->
            <span class="van-ellipsis">
              <van-notice-bar scrollable :text="playList[playListIndex].artists[0].name" />
              <!-- {{ playList[playListIndex].artists[0].name }} -->
            </span>
            <span v-if="duration" style="margin-left: 10px;">
              {{ startTime }}/{{ endTime }}
            </span>
          </div>

        </div>
      </div>

      <!-- 右侧按钮 -->
      <div class="music-play">
        <div class="play">
          <van-icon name="play-circle-o" v-show="!songPlay" @click="hdPlay" />
          <van-icon name="pause-circle-o" v-show="songPlay" @click="hdPause" />
        </div>
        <div class="list">
          <van-icon name="ascending" @click="hdPlayLists" />
        </div>
      </div>
    </div>

    <!-- 播放列表 -->
    <PlayLists ref="playListRef" @onDelete="playListDel" />

    <!-- 音乐详情 -->
    <MusicDetail class="music-detail" ref="musicDetailRef" :isPlay="songPlay" @hdBtn="hdMusicBtn"
      @changePlay="changePlay" v-model:percentage="percentage" @changeSilder="changeSilder" :startTime="startTime"
      :endTime="endTime" />
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onMounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { PlayStore } from '@/store/playlist'
import { getSongUrl } from '@/request/api/musicApi'
import { Toast } from 'vant'
import * as tool from '@/tool'
import MusicDetail from '@/components/musicPlayer/MusicDetail.vue'
import PlayLists from '@/components/musicPlayer/PlayLists.vue'

const $playStore = PlayStore();
let { playList, playListIndex, updateList, sotreChangeSong, nowPlay } = storeToRefs($playStore);

const audioRef = ref(null);

onMounted(() => {
  initData()
});

const initData = () => {
  getMusicUrl(playList.value[playListIndex.value].musicId, false);  //刷新页面禁止自动播放
  timeupdate()
}

// 获取歌曲URL，获取成功自动播放
let musicId = playList.value[playListIndex.value].musicId;
let musicUrl = ref('');
const getMusicUrl = async (id, autoPlay = true) => {
  if (id != 0) {
    await getSongUrl({ id: id }).then(data => {
      musicUrl.value = data.data[0].url;
    })

    if (autoPlay) hdPlay();
  }
}


// 跳转到歌曲详情
let musicDetailRef = ref();
const toMusicDetail = (list) => {
  if (musicId == 0) return Toast.fail('暂无播放歌曲');

  $playStore.nowPlay = playList.value[playListIndex.value];
  // 显示播放详情页
  musicDetailRef.value.showDetail = true;
}

/**
 * 进度条百分比
 * currentTime  当前时间
 * duration 总时间
 * */
let silderData = reactive({
  percentage: 0,
  currentTime: 0,
  duration: 0,
  startTime: 0.00,
  endTime: 0
})

let { percentage, currentTime, duration, startTime, endTime } = toRefs(silderData)
// return {...silderData}

const timeupdate = () => {
  $playStore.upDateNowPlayTime(audioRef.value.currentTime)

  // 秒为格式
  currentTime.value = audioRef.value.currentTime.toFixed(2);
  duration.value = nowPlay.value.duration

  // 格式化时间
  startTime.value = tool.timeFormat(currentTime.value);
  endTime.value = tool.timeFormat(duration.value);

  //当前进度百分比
  let percent = (currentTime.value / duration.value * 100).toFixed(2);
  percentage.value = Number(percent)
}

// 子组件拖动进度条的时候
const changeSilder = (data) => {
  currentTime.value = parseInt(audioRef.value.currentTime);
  duration.value = parseInt(nowPlay.value.duration);

  percentage.value = data;
  currentTime.value = (duration.value * data / 100).toFixed(2);  //跳转到的秒数
  audioRef.value.currentTime = currentTime.value;

  hdPlay();// 如果暂停的时候，开始播放
}

// 歌单有变化时，会暂停当前，重新获取新的URL并播放
watch(playList, (newval, oldval) => {
  console.log('playList改变', newval, oldval);
  if (newval) {
    Toast.loading({
      message: "正在加载",
      duration: 0,
      forbidClick: true
    })

    // 点击全部默认，播放第一首歌曲
    playListIndex.value ? playListIndex.value : 0;
    musicId = newval[playListIndex.value].musicId;
    getMusicUrl(musicId);
  }
})

// 歌单下标变化
watch(playListIndex, (newval, oldval) => {
  console.log('playListIndex  改变');
  // hdPause()
  if (newval != oldval) {
    Toast.loading({
      message: "正在加载",
      duration: 0,
      forbidClick: true
    })

    // 直接改变Index 不改变歌曲列表
    musicId = playList.value[newval].musicId;
    getMusicUrl(musicId);
  }
})

// 歌曲详情里的回调
const hdMusicBtn = (data) => {
  Toast.loading({
    message: '请稍等',
    duration: 0,
    forbidClick: true
  });

  switch (data) {
    case 'play':
      hdPlay();
      break;
    case 'pause':
      hdPause();
      break;
    case 'playList':
      hdPlayLists();
      break;
    case 'playPre':
      hdPlayPre();
      break;
    case 'playNext':
      hdPlayNext();
      break;
  }
}

// 播放
let songPlay = ref(false);
const hdPlay = () => {
  Toast.clear();
  if (musicId == 0) return Toast.fail('播放列表暂无歌曲');

  if (!musicUrl.value) {
    //刷新后没有播放链接，重新获取播放链接
    getMusicUrl(musicId);
  } else {
    audioRef.value.play();
    songPlay.value = true;
  }
}

// 暂停
const hdPause = () => {
  Toast.clear()
  audioRef.value.pause();
  songPlay.value = false;
}

// 子组件播放、暂停按钮
const changePlay = (data) => {
  songPlay.value = data
}

// 点击播放列表
const playListRef = ref();
const hdPlayLists = () => {
  playListRef.value.showPlayLists = true
}

// 播放上一首
const hdPlayPre = () => {
  Toast.clear()
  if (playListIndex.value <= 0) return Toast.fail('已经是第一首了');
  playListIndex.value--;
  $playStore.sotreChangeSong(playListIndex.value)
}

// 播放下一首
const hdPlayNext = () => {
  Toast.clear()
  if (playListIndex.value >= playList.value.length) return Toast.fail('已经是最后一首了');
  playListIndex.value++;
  console.log('开始改变');
  $playStore.sotreChangeSong(playListIndex.value)
}

// 播放列表删除
const playListDel = (data) => {
  getMusicUrl(data);
}
</script>
  
<style lang='less' scoped>
.music-detail {
  z-index: 99;
}

.slider {
  width: 0;
  height: 2px;
  background: red;
}

.flex {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
}

.player {
  width: 100%;
  height: 100px;
  background-color: #fff;
  padding: 0 30px;
  box-sizing: border-box;
  padding-top: 10px;
  position: relative;



  .music-info {
    display: flex;
    height: 100%;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;

    .info-left {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: space-between;
      width: 80%;

      .music-img {
        width: 80px;
        height: 80px;
        transform: rotate(0deg);
        animation: rotation 8s linear infinite;
        animation-play-state: paused;

        &.round-img {
          animation-play-state: running;
        }

        img {
          border-radius: 50%;
          width: 100%;
          height: 100%;
        }
      }
    }


    @keyframes rotation {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }


    .music-ar {
      width: 70%;
      margin-left: 20px;
      flex: 1;
      font-size: 35px;

      .van-notice-bar {
        height: 20px;
        line-height: 20px;
        padding: 0;
        color: #000;
        font-size: 20px;
        line-height: normal;
        background: none;
      }

      .name {
        font-weight: bold;
        max-width: 400px;
      }

      span {
        font-size: 28px;
      }

      .info {
        display: flex;
        align-items: center;

        .van-ellipsis {
          width: 40%;
        }
      }
    }

    .music-play {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: space-between;
      flex: 1;

      .van-icon {
        font-size: 50px;
      }

      .play {
        // margin-right: 20px;

        i {
          margin: 0 10px;
          font-size: 60px;
        }
      }
    }
  }
}
</style>